# _*_ encoding='utf-8' _*_

from django.shortcuts import render
from django.views.generic import View

from .models import CourseOrg, City
# Create your views here.
from pure_pagination import PageNotAnInteger, Paginator


class OrgView(View):
    def get(self, request):
        all_orgs = CourseOrg.objects.all()
        all_cities = City.objects.all()
        hot_orgs = all_orgs.order_by("-click_nums")[:5]
        city_id = request.GET.get('city', '')
        category = request.GET.get('ct', '')
        sort = request.GET.get('sort', '')

        if(category):
            all_orgs = all_orgs.filter(category=category)
        if(city_id):
            all_orgs = all_orgs.filter(city_id=int(city_id))
        if(sort == 'students'):
            all_orgs = all_orgs.order_by('-student_nums')
        elif(sort == 'courses'):
            all_orgs = all_orgs.order_by('-course_nums')
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        orgs_count = all_orgs.count()
        p = Paginator(all_orgs, 5, request=request)
        org = p.page(page)
        return render(request, 'org_list.html',
                      {'all_orgs': org,
                       'all_cities': all_cities,
                       'orgs_count': orgs_count,
                       'city_id': city_id,
                       'category': category,
                       'hot_orgs': hot_orgs,
                       'sort': sort,
                       })
